<template>
  <div style="width: 100%; height: 100%">
    <div
      :id="getPlayerId"
      ref="ref_video_wrap"
      style="width: 100%; height: 100%"
    />
    <div class="offline" v-if="is_offline">离线</div>
    <div class="offline" v-if="is_offline_2">超时请刷新页面</div>
  </div>
</template>

<script>
import { QNRTPlayer } from "qn-rtplayer-web";
import AgoraRTC from "agora-rtc-sdk-ng";
import { djiAgoraToken, djiAgoraToken2 } from "@/api/kanban";

export default {
  name: "VideoView",
  props: {
    viewId: {
      type: String,
      default: () => "",
    },
    url: {
      type: String,
      default: () => "",
    },
    showControls: {
      type: Boolean,
      default: () => false,
    },
    activeArcUrl: {
      type: Boolean,
      default: () => false,
    },
  },
  watch: {
    url: {
      handler(newVal, oldVal) {
        console.log("videoUrl", newVal);
        if (newVal && newVal !== oldVal) {
          var _this = this;
          this.releasePlayer();
          setTimeout(function () {
            _this.initPlayer();
          }, 500);
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      player: null,
      intervalTask: null,
      hide: false,
      playerType: 0,
      rtcClient: null,
      rtcToken: null,
      rtcChannel: null,
      is_offline: false,
      // 随机用户id 用于直播分享
      random_user_id: 10000,
      is_offline_2: false,
    };
  },
  computed: {
    getPlayerId() {
      return "playerId-" + this.viewId;
    },
  },
  mounted() {
    // this.initQnPlayer()
    // // this.initAliPlayer()
    // this.initIntervalPlay()
  },
  beforeDestroy() {
    if (this.intervalTask) clearInterval(this.intervalTask);
    this.releasePlayer();
  },
  methods: {
    /**
     *  播放器相关
     */
    isQnPlaying() {
      if (this.player && this.player.playerEmitterId) {
        return this.player.playerState === 3;
      }
      return false;
    },
    isAliPlaying() {
      if (this.player && !this.player.playerEmitterId) {
        return this.player.getStatus() === "playing";
      }
      return false;
    },
    releasePlayer() {
      if (this.playerType === 1) {
        if (!this.player) return;
        console.log("releasePlayer Type：" + this.playerType);
        this.player.release();
      } else if (this.playerType === 2) {
        if (!this.player) return;
        console.log("releasePlayer Type：" + this.playerType);
        try {
          this.player.stop();
          this.player.pause();
        } catch (e) {
          console.log(e);
        }
        this.player.dispose();
      } else if (this.playerType === 3) {
        this.leaveClient();
      } else if (this.playerType === 4) {
        if (!this.player) return;
        console.log("releasePlayer JPro播放器");
        this.player.destroy();
        this.player = null;
      }
      this.player = null;
      this.playerType = 0;
      clearTimeout(this.timeoutId);
      this.timeoutId = null;
      this.is_offline_2 = false;
    },
    refreshComp() {
      console.log("refreshComp", this.playerType);
      if (this.playerType === 1) {
        this.initQnPlayer();
      } else if (this.playerType === 2) {
        // this.player && this.player.replay()
        this.initAliPlayer();
      } else if (this.playerType === 3) {
        this.initAgoraPlayer();
      } else if (this.playerType === 4) {
        if (this.player)
          this.player.destroy().then(() => {
            this.player = null;
            if (this.$route.path == "/sharedVideo") {
              this.initAliPlayer();
            } else {
              this.initJProPlayer();
            }
          });
      } else {
        console.log("不支持");
      }
    },
    generateRandomInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    },
    initPlayer() {
      var uurl = this.url;
      // var uurl = "channel=test"
      // this.initQnPlayer();
      if (uurl.indexOf("qvs-live") != -1) {
        // this.initQnPlayer();
        this.initJProPlayer();
      } else if (uurl.indexOf("channel") != -1) {
        var value = uurl.split("=")[1];

        if (this.$store.getters.userId) {
          djiAgoraToken({
            channel: value,
          }).then((res) => {
            if (res.data) {
              this.rtcToken = res.data;
              this.rtcChannel = value;
              this.initAgoraPlayer();
            } else {
              console.log("rtc token fail");
            }
          });
        } else {
          this.random_user_id = this.generateRandomInteger(10000, 20000);
          // 分享状态下
          djiAgoraToken2({
            channel: value,
            user_id: this.random_user_id,
          }).then((res) => {
            if (res.data) {
              this.rtcToken = res.data;
              this.rtcChannel = value;
              this.initAgoraPlayer();
            } else {
              console.log("rtc token fail");
            }
          });
        }
      } else {
        if (this.$route.path == "/sharedVideo" && this.isMobile()) {
          this.initAliPlayer();
        } else {
          this.initJProPlayer();
        }
      }
    },
    initQnPlayer() {
      var _this = this;
      this.releasePlayer();
      // test this.url = 'https://qvs-live.flysee.com:447/flysee/20221124hushan.flv'
      console.log("initOriPlayer url:", this.getPlayerId + ":" + this.url);
      // this.$message("initOriPlayer url111:" +  this.getPlayerId + ":" + this.url);
      const src = this.getQnPlayerUrl();
      // QNRTPlayer.setLogLevel('warning')
      this.player = new QNRTPlayer();
      this.playerType = 1;

      // 2. 初始化配置信息
      this.player.init({ volumn: 0, controls: this.showControls });
      // 3. 传入播放地址及容器，开始播放
      try {
        this.player.play(src, document.getElementById(this.getPlayerId));
        setTimeout(() => {
          if (this.$refs.ref_video_wrap.firstChild) {
            this.$refs.ref_video_wrap.firstChild.disablePictureInPicture = true;
          }
          var qnres = this.player.getPlayerSupport();
          console.log(qnres);
          if (qnres && qnres.peerConnection == false) {
            // 不支持七牛webrtc 切换阿里播放器
            console.log("webrtc不支持");
            // this.initAliPlayer();
            // this.initJProPlayer()
            if (_this.$route.path == "/sharedVideo" && _this.isMobile()) {
              _this.initAliPlayer();
            } else {
              _this.initJProPlayer();
            }
          }
        }, 1000);

        this.player.on("error", (e) => {
          console.log("initQnPlayer error", e);
          if (e["code"] == 20007) {
            // this.releasePlayer();
            this.is_offline = true;
            console.log("网络错误，视频重新连接中...");
            if (this.isMobile()) {
              // this.initAliPlayer();
              // this.initJProPlayer()
              if (_this.$route.path == "/sharedVideo") {
                _this.initAliPlayer();
              } else {
                _this.initJProPlayer();
              }
            } else {
              // this.player.play(src, document.getElementById(this.getPlayerId));
              this.initJProPlayer();
              // if(_this.$route.path=='/sharedVideo'){
              //   _this.initAliPlayer();
              //   }else{
              //     _this.initJProPlayer()
              //   }
            }
          } else if (e["code"] == 20004) {
            console.log("没有流");
            this.$message({
              message: "没有收到视频流信号，请点击刷新按钮重试",
              type: "warning",
            });
          } else if (e["code"] == 20001) {
            console.log("网络错误，改为阿里播放器flv播放");
            // this.initAliPlayer();
            // this.initJProPlayer()
            if (_this.$route.path == "/sharedVideo" && _this.isMobile()) {
              _this.initAliPlayer();
            } else {
              _this.initJProPlayer();
            }
          } else if (e["code"] == 20006) {
            console.log("网络错误，改为阿里播放器flv播放");
            // this.initAliPlayer();
            // this.initJProPlayer()
            if (_this.$route.path == "/sharedVideo" && _this.isMobile()) {
              _this.initAliPlayer();
            } else {
              _this.initJProPlayer();
            }
          } else {
            this.is_offline = true;
            console.log("视频重新连接中...");
            // this.player.play(src, document.getElementById(this.getPlayerId));
            // this.initJProPlayer()
            if (_this.$route.path == "/sharedVideo" && _this.isMobile()) {
              _this.initAliPlayer();
            } else {
              _this.initJProPlayer();
            }
          }
        });
        this.player.on("playerStateChanged", (state) => {
          console.log(state);
          if (state == 3 && this.is_offline) {
            this.is_offline = false;
          } else if (state == 0 && !this.is_offline) {
            console.log("视频状态改变为0");
            this.is_offline = true;
          }
        });
      } catch (e) {
        console.log("initQnPlayer catch", e);
        // this.releasePlayer();
        // this.initAliPlayer();
        this.is_offline = true;
      }
    },
    initAliPlayer() {
      if (this.player) {
        this.releasePlayer();
      }
      // this.url = 'https://qvs-live.flysee.com:447/flysee/20221124hushan.flv'
      console.log("initAliPlayer url:", this.getPlayerId + ":" + this.url);
      const option = {
        id: this.getPlayerId,
        // source: this.getArtcUrl(), // artc 地址，
        source: this.getArtcUrl(), // 播放地址，可以是第三方直播地址，或阿里云直播服务中的拉流地址。
        rtsFallbackSource: this.url,
        videoHeight: "100%", // 容器的大小
        videoWidth: "100%", // 容器的大小
        isLive: true, // 是否为直播播放。
        autoplay: true,
        playsinline: true,
        controlBarVisibility: "never",
        skipRtsSupportCheck: false,
        // rtsLoadDataTimeout: 2000,
        // liveRetry: 1
      };
      console.log("initAliPlayer", option);
      this.player = new Aliplayer(option);
      setTimeout(() => {
        if (this.$refs.ref_video_wrap.firstChild) {
          this.$refs.ref_video_wrap.firstChild.disablePictureInPicture = true;
        }
      }, 1000);
      this.playerType = 2;

      this.initAliPlayerListener();
    },
    initJProPlayer() {
      if (this.player) {
        this.releasePlayer();
      }
      this.is_offline = false;
      this.is_offline_2 = false;
      console.log("JPro播放器");
      this.playerType = 4;
      var options = {};
      this.player = new window.JessibucaPro(
        Object.assign(
          {
            decoder: "/js/jessibuca/decoder-pro.js",
            container: document.getElementById(this.getPlayerId),
            videoBuffer: 0.2, // 缓存时长
            isResize: false,
            useWCS: false,
            useMSE: true,
            useSIMD: false,
            text: "",
            loadingText: "疯狂加载中...",
            debug: false,
            supportDblclickFullscreen: false,
            showBandwidth: false, // 显示网速
            operateBtns: {
              fullscreen: false,
              screenshot: false,
              play: false,
              audio: false,
            },
            forceNoOffscreen: false,
            isNotMute: true,
            timeout: 10,
          },
          options
        )
      );
      var _this = this;
      this.player.on("load", function () {
        console.log("on load");
      });
      console.log("initJProPlayerUrl", _this.url, _this.player);
      _this.player.play(_this.url);

      // 设置定时器，在半小时后停止播放
      this.timeoutId = setTimeout(() => {
        this.releasePlayer();
        this.is_offline_2 = true;
      }, 1800 * 1000);
    },
    getQnPlayerUrl() {
      let src = this.url.replace("http://", "webrtc://");
      src = src.replace("https://", "webrtc://");
      // 地址转换 区分http 和https
      if (location.protocol === "http:") {
        src = src.replace("447", "1240");
        src = src.replace("8000", "1240");
        src = src.replace("1360", "1240");
      } else if (location.protocol === "https:") {
        src = src.replace("1240", "447");
      }
      src = src.slice(0, src.length - 4);
      console.log("initQNPlayer url:" + this.getPlayerId + ":" + src);
      return src;
    },
    isMobile() {
      const userAgentInfo = navigator.userAgent;
      const mobileAgents = [
        "Android",
        "iPhone",
        "SymbianOS",
        "Windows Phone",
        "iPad",
        "iPod",
      ];

      for (let i = 0; i < mobileAgents.length; i++) {
        if (userAgentInfo.indexOf(mobileAgents[i]) > 0) {
          return true;
        }
      }

      return false;
    },
    getArtcUrl() {
      if (this.url.indexOf("live02") != -1) {
        if (this.url.indexOf("http://") != -1) {
          var src = this.url.replace("http://", "artc://");
        } else if (this.url.indexOf("https://") != -1) {
          var src = this.url.replace("https://", "artc://");
        }
        src = src.slice(0, src.length - 4);
        console.log("AliPlayer artcUrl:" + src);
        return src;
      } else {
        if (this.isMobile()) {
          var src = this.url.replace("flv", "m3u8");
          return src;
        } else {
          return this.url;
        }
      }
    },
    initAliPlayerListener() {
      const that = this;
      this.player.on("play", () => {
        console.log("aliplayer playing");
        if (that.is_offline) {
          that.is_offline = false;
        }
      });
      this.player.on("error", () => {
        console.log("aliplayer error");
        that.is_offline = true;
      });
    },
    closePlaying() {
      if (this.intervalTask) clearInterval(this.intervalTask);
      if (this.intervalPlay) clearInterval(this.intervalPlay);
      this.releasePlayer();
    },

    //兼容agora
    async joinClient(options) {
      let clientRoleOptions = {
        // Set latency level to low latency
        level: 1,
      };
      this.rtcClient.setClientRole(options.role, clientRoleOptions);
      console.log(options);
      await this.rtcClient.join(
        options.appId,
        options.channel,
        options.token,
        options.uid
      );
    },
    async leaveClient() {
      console.log("清除声网播放器");
      this.rtcClient.remoteUsers.forEach((user) => {
        // Destroy the dynamically created DIV containers.
        const playerContainer = document.getElementById(user.uid.toString());
        playerContainer && playerContainer.remove();
      });

      // Leave the channel.
      await this.rtcClient.leave();
    },
    async initAgoraPlayer() {
      if (this.rtcClient) {
        this.leaveClient();
        this.rtcClient = null;
      }
      console.log("声网播放");
      console.log(this.$store.getters.userId);
      this.playerType = 3;
      let options = {
        // Pass your app ID here.
        appId: "7495598a7a2c4b5b9b70460b529b5132",
        // Set the channel name.
        channel: this.rtcChannel,
        // Set the user role in the channel.
        role: "audience",
        // Use a temp token
        token: this.rtcToken,
        // Uid
        uid: this.$store.getters.userId
          ? parseInt(this.$store.getters.userId)
          : this.random_user_id,
      };

      this.rtcClient = AgoraRTC.createClient({
        mode: "live",
        codec: "vp8",
      });
      this.joinClient(options);

      this.rtcClient.on("user-published", async (user, mediaType) => {
        // Subscribe to a remote user.
        await this.rtcClient.subscribe(user, mediaType);
        console.log("subscribe success");
        console.log(mediaType);
        // If the subscribed track is video.
        if (mediaType === "video") {
          // Get `RemoteVideoTrack` in the `user` object.
          const remoteVideoTrack = user.videoTrack;
          // Dynamically create a container in the form of a DIV element for playing the remote video track.
          const remotePlayerContainer = document.createElement("div");
          // Specify the ID of the DIV container. You can use the `uid` of the remote user.
          remotePlayerContainer.id = user.uid.toString();
          remotePlayerContainer.style.width = "100%";

          const pathname = window.location.href;
          // if (pathname.includes("sharedVideo")) {
          remotePlayerContainer.style.height = "100%";
          // }else{
          //   remotePlayerContainer.style.height = "calc(100% - 30px)";
          // }

          document
            .getElementById(this.getPlayerId)
            .append(remotePlayerContainer);

          // Play the remote video track.
          // Pass the DIV container and the SDK dynamically creates a player in the container for playing the remote video track.
          remoteVideoTrack.play(remotePlayerContainer);
          this.is_offline = false;
        }
      });

      this.rtcClient.on("user-unpublished", (user) => {
        // Get the dynamically created DIV container.
        const remotePlayerContainer = document.getElementById(user.uid);
        // Destroy the container.
        remotePlayerContainer.remove();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .loading-center {
  visibility: hidden;
}

::v-deep .prism-controlbar {
  display: none !important;
}

::v-deep .prism-ErrorMessage {
  display: none !important;
}

.offline {
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
#playerId-aircraftVideoMobile {
  height: 100vw !important;
}
#playerId-aircraftVideoPc {
  ::v-deep video {
    object-fit: fill !important;
  }
}
</style>
